/**
 * DBTemplateManager.java
 *
 * Copyright 2010 @company@, Inc.
 *
 * @company@ licenses this file to you under the Apache License, version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License.  You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.zaoke.web.common;

import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;


/**
 * Manage database templates, including read templates and write template.
 * 
 * @author @author@ (@author-email@)
 * 
 * @version @version@, $Date: 2010-12-31$
 *
 */
public class DBTemplateManager {
	private SimpleJdbcTemplate[] readTps;
	private SimpleJdbcTemplate writeTp;

	/**
	 * get one of the read templates from the managed pool randomly.
	 * 
	 * @return a read template
	 * @throws IllegalStateException if read templates not set.
	 */
	public SimpleJdbcTemplate getReadTp() {
	    if (readTps == null) {
	        throw new IllegalStateException("ReadTp is null!");
	    }
		int idx = (int)(readTps.length * Math.random());
		return readTps[idx];
	}

	/**
	 * set read templates into managed pool.
	 * 
	 * @param readTps read templates
	 */
	public void setReadTps(SimpleJdbcTemplate[] readTps) {
		this.readTps = readTps;
		for (SimpleJdbcTemplate readTp : readTps)
			readTp.queryForObject("select now();", String.class);
	}

	/**
     * get the write template from the managed pool.
     * 
     * @return the write template
     * @throws IllegalStateException if write template not set.
     */
	public SimpleJdbcTemplate getWriteTp() {
	    if (writeTp == null) {
            throw new IllegalStateException("writeTp is null!");
        }
		return writeTp;
	}

	/**
     * set write template into managed pool.
     * 
     * @param writeTp write template
     */
	public void setWriteTp(SimpleJdbcTemplate writeTp) {
		this.writeTp = writeTp;
	}

}
